
package com.zhu.salesmanagement.network;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.zhu.salesmanagement.R;
import com.zhu.salesmanagement.VisitTaskListActivity;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.models.CustomerShelfsItem;
import com.zhu.salesmanagement.models.ProductInfo;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.Util;
import com.zhu.salesmanagement.views.ProductInfoListView;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;


/**
 * 拜访 货架 CRC等数据获取
 */

public class CustomerShelfData {

    private Context mContext = null;
    private String sEmployeeID = null;
    private String mUuid = null;
    private String[] mFloorType = null;
    private String[] mProductInfoType = null;
    private List<Object> mVisitedList = new ArrayList<Object>(); //门店拜访
    private List<Object> mShelfList = new ArrayList<Object>(); //货架信息
    private List<Object> mOtherList = new ArrayList<Object>(); //重要和竞品
    private List<Object> mCRCList = new ArrayList<Object>(); //CRC
    private List<CustomerShelfsItem> mSavedCPList = new ArrayList<CustomerShelfsItem>(); //需要保存的货架信息
    String mWhere = "";

    /**
     * 构造函数
     * @param context 上下文
     * @param eid 业务员ID
     * @param uuid 授权ID
     */
    public CustomerShelfData(Context context, String eid, String uuid) {
        mContext = context;
        sEmployeeID = eid;
        mUuid = uuid;
    }

    /**
     * 获取处理数据
     */
    public void parseData() {
    	mWhere = "";
    	clear();
    	parseVisiedData();
    	parseCustomer();
    }

    /**
     * 处理CRC数据
     */
    private void parseCustomer(){
    	 Cursor cursor = null;
         try {
             cursor = mContext.getContentResolver().query(
                     SalesSettings.GoodsInfoColumns.CONTENT_URI, null, mWhere, null, null);
             final int storeIdIndex = cursor
                     .getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns.STOREID);
             final int goodsTypeIndex = cursor
                     .getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns.TYPEID);
             final int placeIndex = cursor
                     .getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns.PLACE);
             final int floorIndex = cursor
                     .getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns.FLOOR);
             final int typeIndex = cursor
             .getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns.TYPE);
             final int sideIndex = cursor.getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns.SIDE);
             final int jingpinIndex = cursor
                     .getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns.JINGPIN);
             final int importIndex = cursor
                     .getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns.IMPORTINFO);
             final int goodsIndex = cursor
                     .getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns.GOODS);
             final int dtaidIndex = cursor.getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns.DTASKACTUALID);
             final int timeIndex = cursor.getColumnIndexOrThrow(SalesSettings.GoodsInfoColumns.CREATE_TIME);

             while (cursor.moveToNext()) {
                 String cid = cursor.getString(storeIdIndex);
                 String dtaid = cursor.getString(dtaidIndex);
                 long time = Long.parseLong(cursor.getString(timeIndex));
                 if(Actions.DEBUG){
                     Log.e("zhu", "cid=" + cid +"  dtaid="+dtaid);
                 }
                 List<Object> cplist = getCustomerCPlist(getShelfCustomerMap(cid, mShelfList)); //获取货架信息
                 List<Object> otherlist = getCustomerOtherlist(getOtherCustomerMap(cid, mOtherList, dtaid)); //其他信息
                 Map<String, Object> map = new HashMap<String, Object>();
                 String cpid = cursor.getString(goodsTypeIndex);
                 int place = cursor.getInt(placeIndex);
                 if(place == ProductInfoListView.INVALID_VALUE){ //位
                	 place = 0;
                 }
                 int side = cursor.getInt(sideIndex);
                 if(side == ProductInfoListView.INVALID_VALUE){ //面
                	 side = 0;
                 }
                 int floor = cursor.getInt(floorIndex);
                 if(floor == ProductInfoListView.INVALID_VALUE){ //层
                     floor = 0;
                 }
                 int type = cursor.getInt(typeIndex);
                 if(type == ProductInfoListView.INVALID_VALUE){ //位置
                     type = 0;
                 }
//                 CustomerShelfsItem item = new CustomerShelfsItem();
//                 item.customerId = cid;
//                 item.sProductCategoryID = cpid;
//                 item.iShelfCount = String.valueOf(place);
//                 item.iShelfLayer = String.valueOf(floor);
//                 item.iShelfArea = String.valueOf(side);
//                 mSavedCPList.add(item);

                 map.put("sProductCategoryID", cpid);
                 map.put("iShelfCount", place);
                 map.put("iShelfLayer", floor/*getFloorText(floor)*/);
                 map.put("iShelfArea", side);
                 map.put("sShelfType", getTypeText(type));
                 //map.put("iStatus", "true");
                 cplist.add(map);
                 if(Actions.DEBUG){
                     Log.e("zhu", "cpsize=" + cplist.size());
                 }
                 Map<String, Object> map2 = new HashMap<String, Object>();
                 map2.put("sProductCategoryID", cpid);
                 String importinfo = cursor.getString(importIndex);
                 String jingpin = cursor.getString(jingpinIndex);
                 if(importinfo == null){
                	 importinfo = "";
                 }
                 if(jingpin == null){
                	 jingpin = "";
                 }
                 map2.put("sImportantMSG", importinfo);
                 map2.put("sCompetitionMSG", jingpin);
                 otherlist.add(map2);
                 Log.e("zhu", "othersize=" + otherlist.size());
                 addCRCList("", cid, cpid, cursor.getString(goodsIndex), dtaid, time); //添加CRC数据
             }
         } catch (Exception e) {
             if (Actions.DEBUG) {
                 e.printStackTrace();
             }
         } finally {
             if (cursor != null) {
                 cursor.close();
                 cursor = null;
             }
         }
    }

    /**
     * 处理门店拜访数据
     */
    private void parseVisiedData(){
    	Cursor cursor = null;
   	 	try{
            cursor = mContext.getContentResolver().query(SalesSettings.VisitedStoresColumns.CONTENT_URI, null, null, null, null);
            final int idIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns._ID);
            final int storeidIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.STOREID);
            final int vcidIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.VISITCATEGOR);
            final int itemnoIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.ITEMNO);
            final int checkintimeIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKIN_TIME);
            final int checkouttimeIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKOUT_TIME);
            final int visitedIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.VISITSTATUS);
            final int taskidIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.TASKID);
            final int taskdateIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.TASTDATE);
            final int aeidIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.AEMPLOYEEID);
            final int checkinLatIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKIN_LAT);
            final int checkinLngIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKIN_LNG);
            final int checkoutLatIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKOUT_LAT);
            final int checkoutLngIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKOUT_LNG);
            final int dtaidIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.DTASKACTUALID);

            String[] tid = getDatingTaskID();
            if(Actions.DEBUG){
                Log.e("zhu", "tid="+tid);
            }
            while (cursor.moveToNext()) {
                String checkintime = cursor.getString(checkintimeIndex);
                if(Actions.DEBUG){
                	Log.e("zhu","checkintime="+checkintime);
                }
                if(checkintime != null && checkintime.length() > 1){
                	Map map = new HashMap<String, Object>();
                    map.put("sDatingTaskActualID", cursor.getString(dtaidIndex)/*Util.getDatingTaskActualID(Util.mVerifyUserResult.id, cursor.getString(storeidIndex))*/);
                    String taskdata = cursor.getString(taskdateIndex);
                    if(taskdata == null || taskdata.trim().length() == 0){
                        taskdata = tid[1];
                    }
                    if(taskdata == null){
                        taskdata = "0";
                    }
                    map.put("dActualDate", new Date(Long.parseLong(taskdata)));

                    map.put("dSignInTime", new Date(Long.parseLong(checkintime)));
                    map.put("decSignInLongitude", Double.parseDouble(cursor.getString(checkinLngIndex)));
                    map.put("decSignInLatitude", Double.parseDouble(cursor.getString(checkinLatIndex)));
                    String checkouttime = cursor.getString(checkouttimeIndex);
                    if(checkouttime != null && checkouttime.length() > 1){
                        map.put("dSignOutTime", new Date(Long.parseLong(checkouttime)));
                        map.put("decSignOutLongitude", Double.parseDouble(cursor.getString(checkoutLngIndex)));
                        map.put("decSignOutLatitude", Double.parseDouble(cursor.getString(checkoutLatIndex)));
                    }else{
                    	map.put("dSignOutTime", new Date(0));
                        map.put("decSignOutLongitude", (double)0);
                        map.put("decSignOutLatitude", (double)0);
                    }
                    
                    String aeid = cursor.getString(aeidIndex);
                    if(aeid == null){
                    	aeid = Util.mVerifyUserResult.id;
                    }
                    String sid = cursor.getString(storeidIndex);
                    map.put("sVisitEmployeeID", aeid);
                    map.put("sCustomerID", sid);
                    map.put("iVisitCategory", cursor.getInt(vcidIndex));

                    String dtid = cursor.getString(taskidIndex);
                    if((dtid == null || dtid.trim().length() == 0) && (sid.equals(VisitTaskListActivity.STARTCHECKID) || sid.equals(VisitTaskListActivity.STOPCHECKID))){
                        dtid = tid[0];
                    }
                    if(dtid == null){
                        dtid = "";
                    }
                    if(Actions.DEBUG){
                    	Log.e("zhu","dtid="+dtid + "," +cursor.getString(dtaidIndex) +",sid="+sid);
                    }
                    map.put("sDatingTaskID", dtid);
                    if(mWhere.length() == 0){
                    	mWhere = SalesSettings.GoodsInfoColumns.STOREID + " = \"" + cursor.getString(storeidIndex) + "\"";
                    }else{
                    	mWhere += " OR " + SalesSettings.GoodsInfoColumns.STOREID + " = \"" + cursor.getString(storeidIndex) + "\"";
                    }
                    mVisitedList.add(map);
                }
            }
        }catch(Exception e){
        	e.printStackTrace();
            if(Actions.DEBUG){
            	Log.e("zhu","getVistedTaskList error");
            }
        }finally{
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
    }

    /**
     * 组装获取信息上传格式数据
     * @param customerId 门店ID
     * @param list 单个大类货架信息
     */
    private Map<String, Object> getShelfCustomerMap(String customerId, List<Object> list) {
        Map<String, Object> map = null;
        for (int i = 0; i < list.size(); i++) {
            map = (Map<String, Object>) list.get(i);
            Iterator<Entry<String, Object>> iter = map.entrySet().iterator();
            while (iter.hasNext()) {
                Entry<String, Object> entry = iter.next();
                String key = entry.getKey();
                Object value = entry.getValue();
                if (key.equals("sCustomerID")) {
                    if (((String) value).equals(customerId)) {
                        return map;
                    }
                }
            }
        }
        map = new HashMap<String, Object>();
        map.put("sCustomerID", customerId);
        list.add(map);
        return map;
    }

    /**
     * 组装重要信息等信息上传格式数据
     * @param customerId 门店ID
     * @param list 单个大类重要和竞品信息
     * @param dtaid sDatingTaskActualID
     */
    private Map<String, Object> getOtherCustomerMap(String customerId, List<Object> list, String dtaid) {
        Map<String, Object> map = null;
        for (int i = 0; i < list.size(); i++) {
            map = (Map<String, Object>) list.get(i);
            Iterator<Entry<String, Object>> iter = map.entrySet().iterator();
            while (iter.hasNext()) {
                Entry<String, Object> entry = iter.next();
                String key = entry.getKey();
                Object value = entry.getValue();
                if (key.equals("sCustomerID")) {
                    if (((String) value).equals(customerId)) {
                        return map;
                    }
                }
            }
        }
        map = new HashMap<String, Object>();
        map.put("sDatingTaskActualID", dtaid/*Util.getDatingTaskActualID(Util.mVerifyUserResult.id, customerId)*/);
        map.put("sCustomerID", customerId);
        list.add(map);
        return map;
    }

    private List<Object> getCustomerCPlist(Map<String, Object> map) {
        List<Object> listcp = (List<Object>) map.get("CustomerShelf");
        if (listcp == null) {
            listcp = new ArrayList<Object>();
            map.put("CustomerShelf", listcp);
        }
        return listcp;
    }

    private List<Object> getCustomerOtherlist(Map<String, Object> map) {
        List<Object> listcp = (List<Object>) map.get("DatingTaskActualOther");
        if (listcp == null) {
            listcp = new ArrayList<Object>();
            map.put("DatingTaskActualOther", listcp);
        }
        return listcp;
    }

    /**
     * 添加CRC考核数据
     * @param taskid 
     * @param cid sCustomerID
     * @param pcid sProductCategoryID
     * @param goods 产品考评结果
     * @param dtaid sDatingTaskActualID
     */
    private void addCRCList(String taskid, String cid, String pcid, String goods, String dtaid, long time){
    	if(goods == null || goods.trim().length() == 0){
    		if (Actions.DEBUG) {
                Log.e("zhu", "not have product=" + pcid);
            }
    		return;
    	}
    	String[] rowGoods = goods.split(ProductInfoListView.SPLIT_ROW);
        for (int i = 0; i < rowGoods.length; i++) {
            if (Actions.DEBUG) {
                Log.e("zhu", "xx=" + rowGoods[i]);
            }
            String[] rankGoods = rowGoods[i].split(ProductInfoListView.SPLIT_RANK);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("sDatingTaskActualID", dtaid/*Util.getDatingTaskActualID(Util.mVerifyUserResult.id, cid)*/);
            map.put("sCustomerID", cid);
            map.put("sProductCategoryID", pcid);
            map.put("sProductID", rankGoods[0]);
            if(rankGoods.length > 2){
            	if (rankGoods[1].equals(ProductInfoListView.DEFAULT)) {
                    rankGoods[1] = "-1";
                }
            	map.put("iShelfLayer", Integer.parseInt(rankGoods[1]));
            	if (rankGoods[2].equals(ProductInfoListView.DEFAULT)) {
                    rankGoods[2] = "-1";
                }
            	map.put("iShelfArea", Integer.parseInt(rankGoods[2]));
            	if (rankGoods[3].equals(ProductInfoListView.DEFAULT)) {
            		rankGoods[3] = "-1";
            	}
            	map.put("decStockQty", Double.parseDouble(rankGoods[3]));
            	if (rankGoods[4].equals(ProductInfoListView.DEFAULT)) {
            		rankGoods[4] = "";
            	}
            	map.put("sSpecialExhibitionID",  rankGoods[4]);
            	map.put("decStorePrice",  Double.parseDouble("-1"/*rankGoods[4]*/));
            }else{
            	if (rankGoods[1].equals(ProductInfoListView.DEFAULT)) {
                    rankGoods[1] = "-1";
                }
            	map.put("iShelfLayer", -1);
            	map.put("iShelfArea", -1);
            	map.put("decStockQty", Double.parseDouble(rankGoods[1]));
            	map.put("decStorePrice",  -1);
            	map.put("sSpecialExhibitionID", "");
            }
            map.put("dCreateDate", new Date(time));
            mCRCList.add(map);
        }
    }

    public List<Object> getShelfList(){
    	if(mShelfList.size() > 0){
    		return mShelfList;
    	}
    	return null;
    }

    public List<Object> getOtherList(){
    	if(mOtherList.size() > 0){
    		return mOtherList;
    	}
    	return null;
    }

    public List<Object> getCRCList(){
    	if(mCRCList.size() > 0){
    		return mCRCList;
    	}
    	return null;
    }

    public List<CustomerShelfsItem> getSaveCPlist(){
    	return mSavedCPList;
    }

    public Object[] getShelfObject(){
    	if(Actions.DEBUG){
    		Log.e("zhu","getShelfObject="+mShelfList.size());
    	}
    	if(mShelfList.size() > 0){
    		return new Object[]{sEmployeeID, mUuid, mShelfList};
    	}else{
    		return null;
    	}
    }

    public Object[] getOtherObject(){
    	if(Actions.DEBUG){
    		Log.e("zhu","getOtherObject="+mOtherList.size());
    	}
    	if(mOtherList.size() > 0){
    		return new Object[]{sEmployeeID, mUuid, mOtherList};
    	}else{
    		return null;
    	}
    }

    public Object[] getCRCObject(){
    	if(Actions.DEBUG){
    		Log.e("zhu","getCRCObject="+mCRCList.size());
    	}
    	if(mCRCList.size() > 0){
    		return new Object[]{sEmployeeID, mUuid, mCRCList};
    	}else{
    		return null;
    	}
    }

    public Object[] getVisitedTaskObject(){
    	if(Actions.DEBUG){
    		Log.e("zhu","getVisitedTaskObject="+mVisitedList.size());
    	}
    	if(mVisitedList.size() > 0){
    		return new Object[]{sEmployeeID, mUuid, mVisitedList};
    	}else{
    		return null;
    	}
    }

    private void clear(){
    	if(mShelfList != null){
    		mShelfList.clear();
    	}
    	if(mOtherList != null){
    		mOtherList.clear();
    	}
    	if(mCRCList != null){
    		mCRCList.clear();
    	}
    	if(mVisitedList != null){
    		mVisitedList.clear();
    	}
    	if(mSavedCPList != null){
    		mSavedCPList.clear();
    	}
    }

    public void destory(){
    	if(mShelfList != null){
    		mShelfList.clear();
    		mShelfList = null;
    	}
    	if(mOtherList != null){
    		mOtherList.clear();
    		mOtherList = null;
    	}
    	if(mCRCList != null){
    		mCRCList.clear();
    		mCRCList = null;
    	}
    	if(mVisitedList != null){
    		mVisitedList.clear();
    		mVisitedList = null;
    	}
    	if(mSavedCPList != null){
    		mSavedCPList.clear();
    		mSavedCPList = null;
    	}
    }

    /**
     * 清除保存的数据
     */
    public void delteSqData(){
        if(Util.isEndVisit(mContext)){
            if(Actions.DEBUG){
                Log.e("zhu","delete All data");
            }
            mContext.getContentResolver().delete(SalesSettings.VisitedStoresColumns.CONTENT_URI, null/*"visit = 1"*/, null);
            mContext.getContentResolver().delete(SalesSettings.GoodsInfoColumns.CONTENT_URI, mWhere, null);
        }
    }

    /**
     * 获取DatingTaskID
     */
    private String[] getDatingTaskID(){
        String[] id = new String[2];
        Cursor cursor = null;
        try{
            cursor = mContext.getContentResolver().query(SalesSettings.VisitedStoresColumns.CONTENT_URI, new String[]{ SalesSettings.VisitedStoresColumns.TASKID , SalesSettings.VisitedStoresColumns.TASTDATE}, null, null, null);
            while (cursor.moveToNext()) {
                String tid = cursor.getString(cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.TASKID));
                if(tid != null && tid.trim().length() > 0){
                    id[0] = tid;
                }
                String data = cursor.getString(cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.TASTDATE));
                if(data != null && data.trim().length() > 0){
                    id[1] = data;
                    break;
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            id[0] = null;
            id[1] = null;
        }finally{
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        return id;
    }

    private String getFloorText(int selectIndex){
    	if(mFloorType == null){
    		mFloorType = mContext.getResources().getStringArray(R.array.floor_type);
    	}
    	if(selectIndex >= 0 && selectIndex < mFloorType.length){
    		return mFloorType[selectIndex];
    	}
    	return "";
    }

    /**
     * 获取货架位置
     */
    private String getTypeText(int selectIndex){
        if(mProductInfoType == null){
            mProductInfoType = mContext.getResources().getStringArray(R.array.productinfo_type);
        }
        if(selectIndex >= 0 && selectIndex < mProductInfoType.length){
            return mProductInfoType[selectIndex];
        }
        return "";
    }
}
